package controller

import (
	"blog/dao"
	"encoding/json"
	"errors"
	"fmt"
	"github.com/julienschmidt/httprouter"
	"net/http"
	"strings"
	"time"
)

func TestHandle(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	//indexName := dao.EsConf["INDEX_NAME_POST"]
	types := dao.GetTypeList(0, -1)
	strBody, _ := json.Marshal(types)

	w.Write(strBody)
}

//创建索引
func createIndex(indexName string) (err error) {
	err = dao.EsIndexCreate(indexName)
	return
}

//删除索引
func deleteIndex() (err error) {
	indexName := dao.EsConf["INDEX_NAME_POST"]
	err = dao.EsIndexDelete(indexName)
	return
}

//保存所有
func saveAllPost() (err error) {

	infoAll, err := dao.GetAllPost(true)
	if err != nil {
		fmt.Println(err)
		return
	}

	if len(infoAll) < 1 {
		fmt.Println(errors.New("数据为空"))
		return
	}
	type bulkCreate struct {
		Create struct {
			Index string `json:"_index"`
			Type  string `json:"_type"`
			Id    int    `json:"_id"`
		} `json:"create"`
	}

	indexName := dao.EsConf["INDEX_NAME_POST"]
	var jsonStr []string
	for _, info := range infoAll {
		var post dao.ESPosts

		post.Id, post.Author, post.PostType, post.Title, post.Content, post.ReadNum, post.IsPrivate, post.IsShow, post.IsRemark, post.IsTemp, post.IsStar =
			info.Id, info.Author, info.PostType, string(info.Title), string(info.Content), info.ReadNum, info.IsPrivate, info.IsShow, info.IsRemark, info.IsTemp, info.IsStar
		//时间得特殊处理
		CT, _ := time.Parse(dao.TimeLayout, info.AddTime)
		post.AddTime = CT.Format(time.RFC3339)
		UT, _ := time.Parse(dao.TimeLayout, info.LastEditTime)
		post.LastEditTime = UT.Format(time.RFC3339)

		var bulk bulkCreate
		bulk.Create.Id = info.Id
		bulk.Create.Index = indexName
		bulk.Create.Type = indexName
		strHead, _ := json.Marshal(bulk)
		strBody, _ := json.Marshal(post)

		jsonStr = append(jsonStr, fmt.Sprintf("%s\n%s\n", string(strHead), string(strBody)))
	}
	err = dao.EsIndexMultiSave(strings.Join(jsonStr, ""))
	if err != nil {
		fmt.Println(err)
		return
	}

	return
}

//保存一条
func saveOnePost() (err error) {
	info, err := dao.GetPostInfo(2, true)
	if err != nil {
		fmt.Println(err.Error())
		return
	}

	indexName := dao.EsConf["INDEX_NAME_POST"]
	var post dao.ESPosts
	post.Id, post.Author, post.PostType, post.Title, post.Content, post.ReadNum, post.IsPrivate, post.IsShow, post.IsRemark, post.IsTemp, post.IsStar =
		info.Id, info.Author, info.PostType, string(info.Title), string(info.Content), info.ReadNum, info.IsPrivate, info.IsShow, info.IsRemark, info.IsTemp, info.IsStar
	//时间得特殊处理
	CT, _ := time.Parse(dao.TimeLayout, info.AddTime)
	post.AddTime = CT.Format(time.RFC3339)
	UT, _ := time.Parse(dao.TimeLayout, info.LastEditTime)
	post.LastEditTime = UT.Format(time.RFC3339)
	strOut, _ := json.MarshalIndent(post, "", "")

	err = dao.EsIndexSaveData(indexName, indexName, string(strOut), post.Id)
	return
}
